Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

231
Views
Can't I move element by using "element.style.top = window.scrollY"?

I'm trying to make some kind of floating input element, making it follows the scroll. finally I made it and there is code below.

What I am wondering about is if i change "setText(window.scrollY)" to "document.querySelector(".code).style.top = window.scrollY" it doesn't give me the same result. I think it is same code but later code doesn't work. Can anybody tell me why? thank you

import React, { useState } from "react";

function Input() {
  const [scroll, setScroll] = useState(0);
  
  window.addEventListener(
    "scroll",
    function () {
      if (typeof document.querySelector(".code") === "undefined") {
        alert("TT");
      } else {
        setScroll(window.scrollY);              // *this part
      }
    },
    { passive: true }
  );

  return (
    <input
      style={{
        top: text
      }}
      className="code"
      autoComplete="on"
      placeholder="Write code please"
    />
  );
}

export default Input;
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

 setScroll(window.scrollY+"px");  
about 4 years ago · Juan Pablo Isaza Report

0

Use the useRef() hook instead of document.querySelector(".code"). React works with virtual DOM, so when document.querySelector(".code") runs, the rea DOM would not be available yet. But you can use useRef to grab the virtual DOM and perform your manipulations on it. You can access the element with the ref's .current property.

Secondly, the scroll event handler would need to be wrapped in React's useEffect hook, to ensure it is added when the component mounts.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!